cmake_minimum_required(VERSION 3.13...3.16)
if (${CMAKE_VERSION} VERSION_LESS 3.16)
  cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
else ()
  cmake_policy(VERSION 3.16)
endif ()

set(PROJECT_NAME UNAP)
project(${PROJECT_NAME}
  LANGUAGES C CXX)

option(UNAP_BUILD_EXAMPLES          "Build examples" ON)
# Set cmake module path
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/src" "${CMAKE_MODULE_PATH}")
include(cMakeUtilities)

# Set default installation directory, but provide a means for users to change
set(UNAP_INSTALL_PREFIX "${PROJECT_SOURCE_DIR}/src/install" CACHE PATH
    "Installation directory ")
set(CMAKE_INSTALL_PREFIX "${UNAP_INSTALL_PREFIX}" CACHE INTERNAL "" FORCE)

# Set default compile optimization flag
set(UNAP_BUILD_TYPE "Release" CACHE STRING
    "Optimization flags: set to Debug, Release, RelWithDebInfo, or MinSizeRel")
if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
  set(CMAKE_BUILD_TYPE "${UNAP_BUILD_TYPE}" CACHE INTERNAL "" FORCE)
  # Set the possible values of build type for cmake-gui
  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
    "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif ()

# static lib
set(BUILD_SHARED_LIBS OFF CACHE INTERNAL "" FORCE)
# Create the  library object
add_library(${PROJECT_NAME})

# Headers and sources: .
set(UNAP_HEADERS "")

# Headers and sources: remaining subdirectories
set(UNAP_DIRS src/base src/matrix src/solvers)
foreach (DIR IN LISTS UNAP_DIRS)
  add_subdirectory(${DIR})
  target_include_directories(${PROJECT_NAME} PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/${DIR}>)
endforeach ()

#target_include_directories(${PROJECT_NAME} PUBLIC
#  $<BUILD_INTERFACE:${UNAP_BINARY_DIR}>
#  $<BUILD_INTERFACE:${UNAP_SOURCE_DIR}>
#  $<INSTALL_INTERFACE:include>
#  )

find_program(MPIEXEC_EXECUTABLE NAMES mpiexec mpirun)
find_package(MPI REQUIRED)
target_link_libraries(${PROJECT_NAME} PUBLIC MPI::MPI_CXX)

# Set OpenMP compile flags
if (USING_OPENMP)
  find_package(OpenMP REQUIRED)
  target_link_libraries(${PROJECT_NAME} PUBLIC OpenMP::OpenMP_CXX)
endif (USING_OPENMP)

# Build the examples directory, if requested
if (UNAP_BUILD_EXAMPLES)
  add_subdirectory(main)
endif ()


include(GNUInstallDirs)
install(TARGETS ${PROJECT_NAME}
  LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
  ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
  RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
  INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")

install(FILES ${UNAP_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
include(CMakePackageConfigHelpers)
add_library(UNAP::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
export(PACKAGE ${PROJECT_NAME})
